class h_evaluation {

	async getStuEvaluationCache(userId) {
		let evaluationData = await this.redis.cache.get(`evaluation@${userId}`, true)
		if(evaluationData)
			return evaluationData
		return false
	}

	async getStuSingleEvaluationCahce(userId, evaluationId) {
		let singleEvaluationData = await this.redis.cache.get(`singleEvaluation@${userId}@${evaluationId}`, true)
		if(singleEvaluationData)
			return singleEvaluationData
		return false
	}

	async clearStuEvaluationCache(userId) {
		return await this.redis.cache.delete(`evaluation@${userId}`)
	}

	async getStuEvaluationData(user) {
		const {userId, session} = user.data.zf
		const reject = (code, msg) => {throw {code, msg}}
		let cookie = {}
	 	cookie[this.config.zf.url] = {
			'ASP.NET_SessionId': session
		}
		const result = await this.common.reqGet({
			url: `${this.config.zf.url}xs_main.aspx`,
			headers: {
				Referer: `${this.config.zf.url}xs_main.aspx?xh=${userId}`
			},
			cookie,
			data: {
				xh: userId
			},
			getStatus: true
		})
		const {status, data} = result
		if(status.code != 200) {
			await this.hd.zf.zfLogout(user)
			return this.reject('-3003', 'zf resources not found')
		}
		const $ = this.common.parseHTML(data)
		const tabIndex = $('.top_link').text().split(' ').indexOf('教学质量评价') - 1
		const list = $('.sub').eq(tabIndex).children('li')
		let evaluationData = []
		list.each(function(index) {
			const temp = $(this).children('a').attr('href').match(/xkkh=(.+)\&xh/)
			if(!temp || !temp[1])
				reject('-3047', 'get evaluation course list item id failed')
			evaluationData.push({
				id: temp[1].trim(),
				name: $(this).text().trim()
			})
		})
		await this.redis.cache.set(`evaluation@${user.userId}`, evaluationData, this.config.frame.sessionExpires.evaluation)
		return evaluationData
	}

	async getStuEvaluationDataById(evaluationId, user) {
		const {userId, session} = user.data.zf
		let cookie = {}
	 	cookie[this.config.zf.url] = {
			'ASP.NET_SessionId': session
		}
		const result = await this.common.reqGet({
			url: `${this.config.zf.url}xsjxpj.aspx`,
			headers: {
				Referer: `${this.config.zf.url}xs_main.aspx?xh=${userId}`
			},
			cookie,
			data: {
				xkkh: evaluationId,
				xh: userId,
				gnmkdm: 'N12141'
			},
			getStatus: true
		})
		const {status, data} = result
		if(status.code != 200) {
			await this.hd.zf.zfLogout(user)
			return this.reject('-3003', 'zf resources not found')
		}
		console.log(data)
		if(/alert\('目前未对你放开教学质量评价'\)/.test(data))
			return this.reject('-3076', 'evaluation teacher not open')
		if(/alert\('你已经评价过!'\)/.test(data)) {
			await this.redis.cache.delete(`evaluation@${user.userId}`)
			return this.reject('-3050', 'this course is evaluated')
		}
		const $ = this.common.parseHTML(data, false)
		const courseName = $('#pjkc option[selected="selected"]').text().trim()
		let evaluations = []
		let contents = []
		$('.datelist tbody tr').each(function(index) {
			const items = $(this).children('td')
			if(index == 0) {
				items.each(function(_index) {
					if(_index < 3)
						return
					evaluations.push({
						tch: $(this).text().trim(),
						evaluation: []
					})
				})
				return
			}
			items.each(function(_index) {
				if(_index == 2) {
					contents.push($(this).text())
				}
				if(_index > 2 && evaluations[_index - 3] && evaluations[_index - 3].evaluation) {
					const map = {
						'优': 'great',
						'良': 'good',
						'中': 'medium',
						'及格': 'pass',
						'差': 'bad'
					}
					evaluations[_index - 3].evaluation.push(map[($(this).children('select').children('option[selected="selected"]').val() || '').trim()] || 'unknown')
				}
			})
		})
		const remark = $('#pjxx').val()
		const evaluationData = {
			courseName,
			evaluations,
			remark
		}
		await this.redis.cache.set(`singleEvaluation@${user.userId}@${evaluationId}`, evaluationData, this.config.frame.sessionExpires.evaluation)
		return evaluationData
	}

	async evaluationTch(evaluationId, evaluationList = [], evaluationRemark = '来自创新盒子速评教', user) {
		const {userId, session} = user.data.zf
		if(!evaluationList instanceof Array || !evaluationList[0] instanceof Array)
			return this.reject('-3051', 'evaluation list invalid')
		if(!this.common.isString(evaluationRemark) || evaluationRemark.length > 50)
			return this.reject('-3052', 'evaluation remark invalid')
		let cookie = {}
	 	cookie[this.config.zf.url] = {
			'ASP.NET_SessionId': session
		}
		const result = await this.common.reqGet({
			url: `${this.config.zf.url}xsjxpj.aspx`,
			headers: {
				Referer: `${this.config.zf.url}xs_main.aspx?xh=${userId}`
			},
			cookie,
			data: {
				xkkh: evaluationId,
				xh: userId,
				gnmkdm: 'N12141'
			},
			getStatus: true
		})
		const {status, data} = result
		if(status.code != 200) {
			await this.hd.zf.zfLogout(user)
			return this.reject('-3003', 'zf resources not found')
		}
		if(/alert\('目前未对你放开教学质量评价'\)/.test(data))
			return this.reject('-3076', 'evaluation teacher not open')
		if(/alert\('你已经评价过!'\)/.test(data))
			return 1
		const $ = this.common.parseHTML(data)
		const courseName = $('#pjkc option[selected="selected"]').text().trim()
		const viewState = $('input[name="__VIEWSTATE"]').val()
		const column = $('.datelisthead td').length - 3
		let reqData = {
			__EVENTTARGET: '',
			__EVENTARGUMENT: '',
			__VIEWSTATE: viewState,
			pjkc: evaluationId,
			pjxx: evaluationRemark,
			TextBox1: 0,
			Button1: '%E4%BF%9D++%E5%AD%98'
		}
		let singleEvaluations = []
		const map = {
			'great': '优',
			'good': '良',
			'medium': '中',
			'pass': '及格',
			'bad': '差'
		}
		for(let i = 1;i <= column;i++) {
			singleEvaluations[i - 1] = {
				evaluation: [],
				tch: $('.datelisthead td').eq(i + 2).text().trim()
			}
			for(let j = 2;j <= 11;j++) {
				let result
				if(evaluationList[i - 1] && evaluationList[i - 1][j - 2]) {
					result = map[evaluationList[i - 1][j - 2]] || '优'
					singleEvaluations[i - 1].evaluation.push(evaluationList[i - 1][j - 2])
				}
				else {
					result = j == 11 ? '良' : '优'
					singleEvaluations[i - 1].evaluation.push(j == 11 ? 'good' : 'great')
				}
				reqData[`DataGrid1:_ctl${j}:JS${i}`] = result
			}
		}
		const result2 = await this.common.reqPost({
			url: `${this.config.zf.url}xsjxpj.aspx`,
			headers: {
				'content-type': 'application/x-www-form-urlencoded',
				Referer: `${this.config.zf.url}xs_main.aspx?xh=${userId}`
			},
			cookie,
			getData: {
				xkkh: evaluationId,
				xh: userId,
				gnmkdm: 'N12141'
			},
			data: reqData,
			getStatus: true
		})
		const {status: status2, data: data2} = result2
		if(status2.code != 200) {
			await this.hd.zf.zfLogout(user)
			return this.reject('-3003', 'zf resources not found')
		}
		await this.redis.cache.set(`singleEvaluation@${user.userId}@${evaluationId}`, {
			courseName,
			evaluations: singleEvaluations,
			remark: evaluationRemark
		}, this.config.frame.sessionExpires.evaluation)
		let evaluationData = await this.redis.cache.get(`evaluation@${user.userId}`, true)
		for(let index in evaluationData) {
			if(evaluationData[index].id == evaluationId) {
				evaluationData[index].evaluated = true
				break
			}
		}
		await this.redis.cache.set(`evaluation@${user.userId}`, evaluationData, this.config.frame.sessionExpires.evaluation)
		console.log(`${user.userId} evaluation tch ${evaluationId} success`)
		return 1
	}

	async submitEvaluationTch(evaluationId, user) {
		const {userId, session} = user.data.zf
		let cookie = {}
	 	cookie[this.config.zf.url] = {
			'ASP.NET_SessionId': session
		}
		const result = await this.common.reqGet({
			url: `${this.config.zf.url}xsjxpj.aspx`,
			headers: {
				Referer: `${this.config.zf.url}xs_main.aspx?xh=${userId}`
			},
			cookie,
			data: {
				xkkh: evaluationId,
				xh: userId,
				gnmkdm: 'N12141'
			},
			getStatus: true
		})
		const {status, data} = result
		if(status.code != 200) {
			await this.hd.zf.zfLogout(user)
			return this.reject('-3003', 'zf resources not found')
		}
		//删除缓存
		await this.redis.cache.delete(`evaluation@${user.userId}`)
		if(/alert\('你已经评价过!'\)/.test(data))
			return 1
		const $ = this.common.parseHTML(data)
		const viewState = $('input[name="__VIEWSTATE"]').val()
		const result2 = await this.common.reqPost({
			url: `${this.config.zf.url}xsjxpj.aspx`,
			headers: {
				'content-type': 'application/x-www-form-urlencoded',
				Referer: `${this.config.zf.url}xs_main.aspx?xh=${userId}`
			},
			cookie,
			getData: {
				xkkh: evaluationId,
				xh: userId,
				gnmkdm: 'N12141'
			},
			data: {
				__EVENTTARGET: '',
				__EVENTARGUMENT: '',
				__VIEWSTATE: viewState,
				pjkc: evaluationId,
				txt1: '',
				TextBox1: 0,
				Button2: '%E6%8F%90++%E4%BA%A4'
			},
			getStatus: true
		})
		const {status: status2, data: data2} = result2
		if(status2.code != 200) {
			await this.hd.zf.zfLogout(user)
			return this.reject('-3003', 'zf resources not found')
		}
		console.log(data2)
		if(!/alert\('您已完成评价！'\)/.test(data2))
			return this.reject('-3049', 'submit evaluation tch failed')
		return 1
	}

}

module.exports = h_evaluation